//
//  New_ROOMVC.m
//  K-Music
//
//  Created by CHUN on 16/1/26.
//  Copyright © 2016年 CHUN. All rights reserved.
//

#import "New_ROOMVC.h"
#define TAG_ALERTVIEW_ChatroomPwd  9999
#define TAG_ALERTVIEW_ChatroomName 9998

@interface New_ROOMVC ()
{
    NSInteger iVoiceMod;
    NSInteger bAutoDelete;
}

@property (nonatomic,strong) UIImageView * tapImageView;

@end

@implementation New_ROOMVC

@synthesize nameTextField;
@synthesize pwdTextField;
@synthesize backView;
@synthesize myScrollView;

- (void)loadView
{
    [super loadView];
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f, 0.0f,WIDTH, HEIGHT/2)];

    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.bounces = NO;
    scrollView.scrollsToTop = NO;
    [self.view addSubview :scrollView];
    self.myScrollView = scrollView;
    self.myScrollView.delegate = self;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 8.0f, WIDTH-20, 20.0f)];
    label.text = @"房间名称";
    
    label.textColor = [UIColor grayColor];
    [self.myScrollView addSubview:label];
    
    self.tapImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(label.frame)+20, 80, 80)];
    self.tapImageView.userInteractionEnabled = YES;
    
    self.tapImageView.image = [UIImage imageNamed:@"Choose_pic"];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(upDateIcon:)];
    [self.tapImageView addGestureRecognizer:tap];
    [self.myScrollView addSubview:self.tapImageView];
    
    
    UITextField *name = [[UITextField alloc] initWithFrame:CGRectMake(90.0f, 3.0f, 210.0f, 35.0f)];
    name.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
//    name.backgroundColor = [UIColor whiteColor];
    name.placeholder = @"请输入房间名";
    self.nameTextField = name;
    self.nameTextField.tag = TAG_ALERTVIEW_ChatroomName;
    self.nameTextField.delegate = self;
    [self.myScrollView addSubview:name];
    
    UILabel *labelPwd = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 55.0f, 80.0f, 20.0f)];
    labelPwd.text = @"房间密码";
    labelPwd.textColor = [UIColor grayColor];
//    [self.myScrollView addSubview:labelPwd];
    
    UITextField *pwd = [[UITextField alloc] initWithFrame:CGRectMake(90.0f, 50.0f, 210.0f, 35.0f)];
    pwd.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    pwd.backgroundColor = [UIColor whiteColor];
    pwd.placeholder = @"请输入1-8位密码（可选）";
    [pwd setSecureTextEntry:YES];
    pwd.keyboardType = UIKeyboardTypeDefault;
    self.pwdTextField = pwd;
    self.pwdTextField.tag = TAG_ALERTVIEW_ChatroomPwd;
    self.pwdTextField.delegate = self;
//    [self.myScrollView addSubview:pwd];
    
    
    UILabel *labelVoiceMod = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 95.0f, 80.0f, 20.0f)];
    labelVoiceMod.text = @"声音设置";
    labelVoiceMod.textColor = [UIColor grayColor];
//    [self.myScrollView addSubview:labelVoiceMod];
    
    NSArray *voiceModArray = [[NSArray alloc]initWithObjects:@"仅有背景音",@"全部提示音",@"无声",nil];
    UISegmentedControl *voiceModSgControl = [[UISegmentedControl alloc]initWithItems:voiceModArray];
    voiceModSgControl.frame = CGRectMake(90.0, 90.0, WIDTH-100, 35.0);
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7)
    {
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
                             [UIFont systemFontOfSize:13],UITextAttributeFont,
                             [UIColor whiteColor],UITextAttributeTextColor,
                             [UIColor blackColor],UITextAttributeTextShadowColor,
                             [NSValue valueWithCGSize:CGSizeMake(1, 1)],UITextAttributeTextShadowOffset,nil];
        [voiceModSgControl setTitleTextAttributes:dic forState:UIControlStateNormal];
    }
    voiceModSgControl.selectedSegmentIndex = 1;//设置默认选择项索引
    voiceModSgControl.segmentedControlStyle = UISegmentedControlStylePlain;
    voiceModSgControl.tag = 1001;
//    [self.myScrollView addSubview:voiceModSgControl];
    [voiceModSgControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    
    UILabel *labelAutoDelete = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 135.0f, 80.0f, 20.0f)];
    labelAutoDelete.text = @"房间类型";
    labelAutoDelete.textColor = [UIColor grayColor];
//    [self.myScrollView addSubview:labelAutoDelete];
    
    NSArray *autoDeleteSgArray = [[NSArray alloc]initWithObjects:@"自动删除房间",@"不自动删除",nil];
    UISegmentedControl *autoDeleteSgControl = [[UISegmentedControl alloc]initWithItems:autoDeleteSgArray];
    autoDeleteSgControl.frame = CGRectMake(90.0, 130.0, WIDTH-100, 35.0);
    autoDeleteSgControl.selectedSegmentIndex = 1;//设置默认选择项索引
    autoDeleteSgControl.segmentedControlStyle = UISegmentedControlStylePlain;
    autoDeleteSgControl.tag = 1002;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7)
    {
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
                             [UIFont systemFontOfSize:13.0f],UITextAttributeFont,
                             [UIColor whiteColor],UITextAttributeTextColor,
                             [UIColor blackColor],UITextAttributeTextShadowColor,
                             [NSValue valueWithCGSize:CGSizeMake(1.0f, 1.0f)],UITextAttributeTextShadowOffset,nil];
        [autoDeleteSgControl setTitleTextAttributes:dic forState:UIControlStateNormal];
    }
//    [self.myScrollView addSubview:autoDeleteSgControl];
    [autoDeleteSgControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    
    UIButton* btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    btn.frame = CGRectMake(0.0f, 170.0f, 290.0f, 30.0f);
    UIImage* img = [UIImage imageNamed:@"choose_on.png"];
    btn.tag = 1;
    [btn setImage: img forState:(UIControlStateNormal)];
    btn.titleLabel.font = [UIFont systemFontOfSize:17.0f];
    [btn setTitle:@"创建人退出时自动解散(单击选择)" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnChooseIsAutoClose:) forControlEvents:(UIControlEventTouchUpInside)];
//    [self.myScrollView addSubview:btn];
    
    UIButton* btnIsAutoJoin = [UIButton buttonWithType:(UIButtonTypeCustom)];
    btnIsAutoJoin.frame = CGRectMake(0.0f, 205.0f, 272.0f, 30.0f);
    UIImage* imgIsAutoJoin = [UIImage imageNamed:@"choose.png"];
    btnIsAutoJoin.tag = 1;
    [btnIsAutoJoin setImage: imgIsAutoJoin forState:(UIControlStateNormal)];
    btnIsAutoJoin.titleLabel.font = [UIFont systemFontOfSize:17.0f];
    [btnIsAutoJoin setTitle:@"创建后自动加入会议(单击选择)" forState:UIControlStateNormal];
    [btnIsAutoJoin setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [btnIsAutoJoin addTarget:self action:@selector(btnChooseIsAutoJoin:) forControlEvents:(UIControlEventTouchUpInside)];
//    [self.myScrollView addSubview:btnIsAutoJoin];
    
    UIButton *createBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    createBtn.frame = CGRectMake(82.0f, 240.0f, WIDTH-164, 38.0f);
    
    createBtn.titleLabel.textColor = [UIColor whiteColor];
    [createBtn setTitle:@"创建" forState:UIControlStateNormal];
    [createBtn setBackgroundImage:[UIImage imageNamed:@"button03_off.png"] forState:UIControlStateNormal];
    [createBtn setBackgroundImage:[UIImage imageNamed:@"button03_on.png"] forState:UIControlStateHighlighted];
    [createBtn addTarget:self action:@selector(createCharRoom:) forControlEvents:UIControlEventTouchUpInside];
//    [self.myScrollView addSubview:createBtn];
//    iVoiceMod = 2;
//    isAutoClose = NO;
//    bAutoDelete = YES;
//    isAutoJoin = NO;
    square = 100;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"创建房间";
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"back" highIcon:@"back" target:self action:@selector(back_back)];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithNameNEW:@"创建" Color:[UIColor blackColor] target:self action:@selector(createCharRoom:)];

    self.view.backgroundColor = RGB(241, 241, 241);
    
}
- (void)back_back
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)viewDidAppear:(BOOL)animated
{
    [self.pwdTextField becomeFirstResponder];
    [self.nameTextField becomeFirstResponder];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

-(void)returnClicked {
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

-(void)segmentAction:(UISegmentedControl *)Seg {
    
    [self.view endEditing:YES];
    switch (Seg.selectedSegmentIndex)
    {
        case 0:
            if(Seg.tag == 1001) {
                iVoiceMod = 1;
            } else {
                bAutoDelete = YES;
            }
            break;
        case 1:
            if(Seg.tag == 1001) {
                iVoiceMod = 2;
            } else {
                bAutoDelete = NO;
            }
            break;
        case 2:
            if(Seg.tag == 1001) {
                iVoiceMod = 3;
            }
            break;
        default:
            break;
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (range.length == 1) {
        return YES;
    }
    
    NSMutableString *text = [textField.text mutableCopy];
    [text replaceCharactersInRange:range withString:string];
    if (textField.tag == TAG_ALERTVIEW_ChatroomPwd) {
        return [text length] <= 8;
    }
    return [text length] <= 50;
}

- (void)createCharRoom:(id)sender
{
    
    if (nameTextField.text.length > 0 && [User_information conversion].Seven_URL_String.length > 0) {
        
        ECCreateMeetingParams *params = [[ECCreateMeetingParams alloc] init];
        params.meetingType = ECMeetingType_MultiVoice;
        params.meetingName = nameTextField.text;
        params.meetingPwd = pwdTextField.text;
        params.square = square;
        params.autoClose = NO;
        params.autoDelete = NO;
        params.voiceMod = 3;//无提示音，无备件音乐
        params.autoJoin = NO;
        
        MBProgressHUD* hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"请稍后...";
        hud.removeFromSuperViewOnHide = YES;
        
        __weak __typeof(self) weakSelf = self;
        [[ECDevice sharedInstance].meetingManager createMultMeetingByType:params completion:^(ECError *error, NSString * meetingNumber) {

            K_ROOM_ID = [meetingNumber copy];
            
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            [MBProgressHUD hideHUDForView:strongSelf.view animated:YES];
            if (error.errorCode == ECErrorType_NoError) {
                
                [self New_RONG_Group];
                
            } else {
                MBProgressHUD* hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.labelText = @"创建会议失败";
                hud.margin = 10.0f;
                hud.removeFromSuperViewOnHide = YES;
                [hud hide:YES afterDelay:2];
            }
        }];
        
    } else {
        MBProgressHUD* hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        
        if ([User_information conversion].Seven_URL_String.length ==0) {
             hud.labelText = @"请选择图片";
        }
        else
        {
            hud.labelText = @"请输入房间名称";
        }
    
        hud.margin = 10.0f;
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:2];
    }
}

#pragma mark - 创建群组 -
- (void)New_RONG_Group
{
    ECGroup * newgroup = [[ECGroup alloc] init];
    newgroup.name = [NSString stringWithFormat:@"K歌王 - %@",nameTextField.text];
    newgroup.declared = @"欢迎来K歌群聊";
    newgroup.isDiscuss = NO;//讨论组该值为YES
    
    [[ECDevice sharedInstance].messageManager createGroup:newgroup completion:^(ECError *error,ECGroup *group) {
        
        if (error.errorCode == ECErrorType_NoError) {
            
            NSLog(@"创建群组成功 群组ID:%@", group.groupId);
            K_GROUP_ID = [group.groupId copy];
            [self create_KGW_room];
            
        }
        else{
            NSLog(@"创建群组失败 errorCode:%d\r\nerrorDescription:%@",
                  (int)error.errorCode,error.errorDescription);
        }
    }];
}

-(void)create_KGW_room
{
    /*
     createdBy (string, optional): 创建者 ,
     createdDate (string, optional): 创建时间 ,
     description (string, optional): 描述 ,
     enterType (integer): 进入房间限制类型: 0: 任何人；1: 仅我关注的人；2:凭密码进入 ,
     groupId (string, optional): 容联群组ID ,
     id (integer, optional): ID ,
     lastModifiedBy (string, optional): 修改者 ,
     lastModifiedDate (string, optional): 修改时间 ,
     name (string, optional): 名字 ,
     password (string, optional): 密码 ,
     peopleNumber (integer, optional): 人数 ,
     pictureUrl (string, optional): 图片URL ,
     popularity (integer, optional): 热度 ,
     singType (integer): 唱歌限制类型:0: 任何人；1: 仅我关注的人； ,
     voiceId (string, optional): 容联语音ID
     */
    
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    
    NSString * token = [FileStorage NSUserDefault_getObjectForKey:access_token];
    
    manager.requestSerializer =[AFJSONRequestSerializer serializer];
    
    [manager.requestSerializer setValue:@"application/json"
                     forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:[NSString stringWithFormat: @"Bearer %@",token]
                     forHTTPHeaderField:@"Authorization"];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString*infoStr11=[NSString stringWithFormat:@"/api/rooms"];
    
    NSString *intactURL = [MyBaseUrl stringByAppendingString:infoStr11];
    
    NSString * createdBy  = [NSString stringWithFormat:@"%@",[FileStorage NSUserDefault_getObjectForKey:User_id]];
    
    NSString * pictureUrl = [NSString stringWithFormat:@"%@",[User_information conversion].Seven_URL_String];
 
    NSDictionary * submit = @{@"createdBy":createdBy,@"pictureUrl":pictureUrl,@"description":nameTextField.text,@"createdBy":pwdTextField.text,@"name":nameTextField.text,@"peopleNumber":@"10",@"voiceId":K_ROOM_ID,@"singType":@0,@"enterType":@0,@"groupId":K_GROUP_ID};
    
    [manager POST:intactURL parameters:submit success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSDictionary * result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
         
         NSLog(@"================:%@",result);
         
         //NSDictionary * body = [result objectForKey:@"body"];
         
         [self get_MyROOM];
         
         [self returnClicked];
         
     }failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"%@", error);
         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"提交失败" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
         [alert show];
     }];
}

- (void)get_MyROOM
{
    [MBProgressHUD showWithStatus:@"加载中..." toView:self.view];
    
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    
    NSString * userId = [NSString stringWithFormat:@"%@",[FileStorage NSUserDefault_getObjectForKey:User_id]];
    
    NSString*infoStr11=[NSString stringWithFormat:@"/api/rooms/user_id/%@?page=0&size=20&sort=createdDate,DESC",userId];
    
    NSString *intactURL = [MyBaseUrl stringByAppendingString:infoStr11];
    
    NSString * token = [FileStorage NSUserDefault_getObjectForKey:access_token];
    
    //    创建请求
    manager.requestSerializer =[AFHTTPRequestSerializer serializer];
    
    [manager.requestSerializer setValue:@"application/json"
                     forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:[NSString stringWithFormat: @"Bearer %@",token]
                     forHTTPHeaderField:@"Authorization"];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:intactURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        
        NSLog(@"成功GET --> MineROOM-%@", dic);
        _KROOMDatas = [NSMutableArray array];
        NSArray * arr = dic[@"body"][@"content"];
        NSArray * Datas = [K_Mode objectArrayWithKeyValuesArray:arr];
        _KROOMDatas = [NSMutableArray arrayWithArray:Datas];
        
        [User_information conversion].MYROOM_Data = [ _KROOMDatas copy];
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@",error);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showErrorWithStatus:@"数据获取失败" toView:self.view];
        
    }];
}

-(void)dealloc
{
    self.nameTextField = nil;
    self.pwdTextField = nil;
    self.myScrollView = nil;
    self.backView = nil;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark -相机-


-(void)upDateIcon:(UITapGestureRecognizer *)sender{
    self.tapImageView =(UIImageView*)sender.view ;
    
    UIActionSheet* actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:nil
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"照相机",@"本地相簿",nil];
    [actionSheet showInView:self.view];
}

#pragma mark                 --------UIActionSheet Delegate--------
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0://照相机
        {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:imagePicker animated:YES completion:nil];
        }
            break;
        case 1://本地相簿
        {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:imagePicker animated:YES completion:nil];
        }
            break;
        default:
            break;
    }
}
#pragma mark           ----------UIImagePickerController Delegate---------
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(__bridge NSString *)kUTTypeImage]) {
        UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
        [self performSelector:@selector(saveImage:)  withObject:img afterDelay:0.5];
        
        NSData *data =  UIImageJPEGRepresentation(img, 0.1);
         [MBProgressHUD showWithStatus:@"图片加载中..." toView:self.view];
        [Seven_httpKeyData requestSeven_token:data sucess:^(id responseObjectUrl) {
            
            NSLog(@"url:%@",responseObjectUrl);
            [User_information conversion].Seven_URL_String = responseObjectUrl;
            [MBProgressHUD hideHUDForView:self.view animated:YES];

            
        } failure:^(id Url) {
            
            
        }];
        
        
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)saveImage:(UIImage *)image {
    [self.tapImageView setImage:image];
}








@end
